package com.gali.mall.filiter;

import com.gali.mall.common.Const;
import com.gali.mall.model.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class UserFilter implements Filter {
    public static User currentUser;
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session =request.getSession();
        currentUser = (User) session.getAttribute(Const.USER_NAME);
        if (currentUser==null){
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) servletResponse).getWriter();
            out.write("{\n "+
                    "\"status\":10007,\n"+
                    "\"msg\":\"NEED_USER_LOGIN\",\n"+
                    "\"data\":null\n"+
                    "}");
            out.flush();
            out.close();
            return;//出错情况下，直接过滤，过滤器不再往下执行
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }
    public void destroy() {
    }
}

